import { httpPost } from "./httpPost";
import { useDeviceUuid } from "./useDeviceUuid";
import { useStorage } from "./useStorage";

/**
 * name 应用
 * title 名称
 * icon 图标
 * version 版本号
 * autor 作者
 * url 下载地址  http://xxxx/name-version.zip
 * @param url 
 */
export function checkPackage(name: string) {
    const SD = files.getSdcardPath()
    const root = files.join(SD, 'sker');
    files.ensureDir(root)
    const downloadDir = files.join(root, 'downloads')
    files.ensureDir(downloadDir)

    const dirPath = files.join(root, `modules/`)
    files.ensureDir(dirPath)

    const packageInfo = httpPost('client/checkPackage', { name, uuid: useDeviceUuid() })
    const storage = useStorage()
    const version = storage.get(`${name}.version`)
    if (version !== packageInfo.version) {
        toastLog(`存在最新版本${packageInfo.version},正在更新...`)
        // 去下载地址下载
        const download = http.get(packageInfo.url) as AutoJs.Response;
        if (download.statusCode === 200) {
            const filePath = files.join(downloadDir, `${name}-${packageInfo.version}.zip`)
            files.createWithDirs(filePath)
            files.writeBytes(filePath, download.body.bytes())
            toastLog(`下载完成,正在解压并安装...`)
            const zipFile = $zip.open(filePath)
            if (!zipFile.isValidZipFile()) {
                throw new Error(`无效zip文件`)
            }
            if (zipFile.isEncrypted()) {
                throw new Error(`文件已加密`)
            }
            zipFile.extractAll(dirPath)
            storage.put(`${name}.version`, packageInfo.version)
            toastLog(`更新并安装完成`)
            return files.join(dirPath, name);
        }
        throw new Error(`下载失败`)
    } else {
        return files.join(dirPath, `${name}`);
    }
}
